package com.wusuowei.auth.controller;

import com.wusuowei.auth.service.impl.ThreeUserServiceImpl;
import com.wusuowei.ucenter.model.po.SysUser;
import com.xkcoding.justauth.AuthRequestFactory;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @description 第三方授权登录
 * @author LGY
 * @date 2023/04/11 18:57
 * @version 1.0.0
 */
@Controller
@RequestMapping("auth/oauth")
public class RestAuthController {

    @Autowired
    AuthRequestFactory factory;
    @Autowired
    ThreeUserServiceImpl threeUserService;


    @GetMapping
    public List<String> list() {
        return factory.oauthList();
    }


    /**
     * @description 给前端二维码
     * @param type 类型
     * @param response 回答
     * @author LGY
     * @date 2023/05/03 19:28
     */
    @GetMapping("/login/{type}")
    public void login(@PathVariable String type, HttpServletResponse response) throws IOException {
        AuthRequest authRequest = factory.get(type);
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }


    /**
     * @description 用户授权后的回调
     * @param type 类型
     * @param callback 回调
     * @return {@link String }
     * @author LGY
     * @date 2023/05/03 19:29
     */
    @GetMapping("/{type}/callback")
    public String callback(@PathVariable String type, AuthCallback callback) {
        AuthRequest authRequest = factory.get(type);
        AuthResponse<AuthUser> response = authRequest.login(callback);
        SysUser sysUser = threeUserService.addUser(response.getData());
        if (sysUser == null) {
            //重定向到一个错误页面
            return "redirect:http://127.0.0.1:8080/login/?error="+"登录失败";
        } else {
            String unionId = sysUser.getUnionid();
            //重定向到登录页面，自动登录
            return "redirect:http://127.0.0.1:8080/login?unionId=" + unionId + "&authType="+type;
        }
    }

}